import React, { useState, useMemo, useEffect } from 'react';
import { Table, Space, Row, Col, Empty, Button, Popover, Checkbox } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import { SettingOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import type { ColumnType, TableProps } from 'antd/es/table';
import type { ReactNode } from 'react';
import type { FormItem } from './DynamicForm';
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';



// 定义列配置接口
interface ListTableColumn<T = any> extends Omit<ColumnType<T>, 'dataIndex'> {
  dataIndex: string;
  hideInSearch?: boolean; // 是否在搜索表单中隐藏
  hideInTable?: boolean; // 是否在表格中隐藏
  valueEnum?: Pick<FormItem, 'options'> | Record<string, { label: string; value?: string }>; // 用于渲染枚举类型的值
  formItemProps?: Omit<FormItem, 'label' | 'name' | 'options'>; // 传递给搜索表单的属性
}

// 定义表格配置接口
interface ListTableProps<T = any> extends Omit<TableProps<T>, 'columns'> {
  columns: ListTableColumn<T>[];
  request: (params: any) => Promise<{ data: T[]; success: boolean; total: number }>;
  dataSource?: T[]; // 如果传入了 dataSource 则不走 request 请求
  toolBarRender?: () => ReactNode[]; // 自定义工具栏
  tableTitle?: ReactNode; // 自定义表格标题
  
  pagination?: {
    pageSize?: number;
    current?: number;
    total?: number;
    showSizeChanger?: boolean;
    showQuickJumper?: boolean;
    onChange?: (page: number, pageSize: number) => void;
  } | false;
}

/**
 * 列表表格组件
 * 整合了搜索表单、表格展示和工具栏功能
 */
const ListTable: React.FC<ListTableProps> = ({
  columns,
  request,
  dataSource: propDataSource,
  toolBarRender,
  tableTitle,
  pagination: propPagination,
  ...tableProps
}) => {
  // 状态管理
  const [data, setData] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [total, setTotal] = useState<number>(0);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [searchParams] = useState<Record<string, any>>({});
  // 列显示状态管理
  const [visibleColumns, setVisibleColumns] = useState<Record<string, boolean>>(() => {
    // 初始化可见列状态，默认所有列都显示（除了明确设置了hideInTable的列）
    const initialVisible: Record<string, boolean> = {};
    columns.forEach(column => {
      initialVisible[column.dataIndex] = !column.hideInTable;
    });
    return initialVisible;
  });
  // 列顺序管理
  const [columnOrder, setColumnOrder] = useState<string[]>(() => {
    // 初始化列顺序，排除操作列
    return columns.filter(column => column.key !== 'action').map(column => column.dataIndex);
  });
  // Popover 可见性状态
  const [settingPopoverVisible, setSettingPopoverVisible] = useState<boolean>(false);

  // 处理分页变化
  const handlePaginationChange = (page: number, size?: number) => {
    setCurrentPage(page);
    if (size) {
      setPageSize(size);
    }

    // 调用用户提供的onChange回调
    if (propPagination && typeof propPagination === 'object' && propPagination.onChange) {
      propPagination.onChange(page, size || pageSize);
    }

    // 重新加载数据
    loadData({ page, pageSize: size || pageSize, ...searchParams });
  };

  // 加载数据
  const loadData = async (params: any) => {
    // 如果提供了dataSource，则直接使用，不发起请求
    if (propDataSource) {
      setData(propDataSource);
      setTotal(propDataSource.length);
      return;
    }

    setLoading(true);
    try {
      const result = await request(params);
      if (result.success) {
        setData(result.data || []);
        setTotal(result.total || 0);
      }
    } catch (error) {
      console.error('Failed to load data:', error);
      setData([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  // 刷新数据
  // const handleRefresh = () => {
  //   loadData({ page: currentPage, pageSize, ...searchParams });
  // };

  // // 处理导出
  // const handleExport = () => {
  //   // 导出功能的基本实现，实际项目中可能需要更复杂的逻辑
  //   console.log('Export data with params:', { page: currentPage, pageSize, ...searchParams });
  // };



  // 处理列显示状态变化
  const handleColumnVisibilityChange = (e: CheckboxChangeEvent, dataIndex: string) => {
    setVisibleColumns(prev => ({
      ...prev,
      [dataIndex]: e.target.checked
    }));
  };

  // 切换所有列的显示状态
  const toggleAllColumns = (checked: boolean) => {
    const newVisible: Record<string, boolean> = {};
    columns.forEach(column => {
      // 排除操作列，确保操作列始终显示
      if (column.key === 'action') {
        newVisible[column.dataIndex || 'action'] = true;
      } else {
        newVisible[column.dataIndex] = checked;
      }
    });
    setVisibleColumns(newVisible);
  };

  // 处理拖拽结束事件 - dnd-kit
  const handleDragEnd = (event: any) => {
    const { active, over } = event;
    
    if (active.id !== over?.id) {
      setColumnOrder((items) => {
        const oldIndex = items.indexOf(active.id);
        const newIndex = items.indexOf(over!.id);
        
        return arrayMove(items, oldIndex, newIndex);
      });
    }
  };

  // 配置拖拽传感器
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  );
  
  // 渲染列设置Popover内容
  const renderColumnSettings = () => {
    const allChecked = columns.every(column => {
      // 操作列不计入全选状态
      if (column.key === 'action') return true;
      return visibleColumns[column.dataIndex] !== false;
    });
    
    // 获取按照columnOrder排序的列
    const orderedColumns = columnOrder.map(dataIndex => 
      columns.find(col => col.dataIndex === dataIndex)
    ).filter(Boolean) as ListTableColumn[];
    
    // 拖拽项组件
    const SortableItem = ({ column }: { column: ListTableColumn }) => {
      // 使用dnd-kit的useSortable hook
      const { 
        attributes,
        listeners,
        setNodeRef,
        transform,
        transition,
      } = useSortable({ id: column.dataIndex });
      
      // 为拖拽项添加样式
      const style: React.CSSProperties = {
        marginBottom: '4px',
        display: 'flex',
        alignItems: 'center',
        padding: '2px 4px',
        borderRadius: '4px',
        transform: CSS.Transform.toString(transform),
        transition,
        backgroundColor: '#fff',
      };
      
      return (
        <div ref={setNodeRef} style={style} {...attributes}>
          <div {...listeners} style={{ cursor: 'grab', marginRight: '8px' }}>
            <MenuUnfoldOutlined 
              style={{ 
                color: '#999',
                fontSize: '14px'
              }} 
            />
          </div>
          <Checkbox 
            checked={visibleColumns[column.dataIndex] !== false}
            onChange={(e) => handleColumnVisibilityChange(e, column.dataIndex)}
            style={{ cursor: 'pointer' }}
          >
            {typeof column.title === 'function' ? String(column.title({})) : column.title}
          </Checkbox>
        </div>
      );
    };
    
    return (
      <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
        <div style={{ marginBottom: '8px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <Checkbox 
            checked={allChecked} 
            onChange={(e) => toggleAllColumns(e.target.checked)}
          >
            全选
          </Checkbox>
          <Button 
            size="small" 
            type="link" 
            onClick={() => toggleAllColumns(true)}
          >
            重置
          </Button>
        </div>
        <div style={{ borderTop: '1px solid #f0f0f0', paddingTop: '8px' }}>
          <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
            <SortableContext items={orderedColumns.map(col => col.dataIndex)} strategy={verticalListSortingStrategy}>
              {orderedColumns.map((column) => {
                // 操作列始终显示，不参与设置
                if (column.key === 'action') {
                  return null;
                }
                return (
                  <SortableItem key={column.dataIndex} column={column} />
                );
              })}
            </SortableContext>
          </DndContext>
        </div>
      </div>
    );
  };
  // 构建表格列配置
  const tableColumns = useMemo(() => {
    // 分离操作列和普通列
    const actionColumn = columns.find(column => column.key === 'action');
    const normalColumns = columns.filter(column => column.key !== 'action');

    // 按照columnOrder对普通列进行排序
    const orderedNormalColumns = columnOrder.map(dataIndex => 
      normalColumns.find(col => col.dataIndex === dataIndex)
    ).filter(Boolean) as ListTableColumn[];

    // 过滤出可见的列
    const visibleOrderedColumns = orderedNormalColumns.filter(column => 
      visibleColumns[column.dataIndex] !== false
    );

    // 处理每列的配置
    const processedColumns = visibleOrderedColumns.map(column => {
      // 克隆列配置，避免直接修改传入的配置
      const tableColumn = { ...column };

      // 如果有valueEnum，添加render函数来显示标签
      if (column.valueEnum) {
        tableColumn.render = (text: any, _record: any) => {
          // 根据valueEnum获取对应的标签
          if (column.valueEnum && 'options' in column.valueEnum && Array.isArray(column.valueEnum.options)) {
            const option = column.valueEnum.options.find((opt: any) => opt.value === text);
            return option ? option.label : text;
          } else if (typeof column.valueEnum === 'object' && !(column.valueEnum as any).options) {
            const valueEnumObj = column.valueEnum as Record<string, { label: string; value?: string }>;
            const option = valueEnumObj[text as string];
            return option ? option.label : text;
          }
          return text;
        };
      }

      return tableColumn;
    });

    // 如果有操作列，将其添加到最后
    if (actionColumn) {
      const tableActionColumn = { ...actionColumn };
      processedColumns.push(tableActionColumn);
    }

    return processedColumns;
  }, [columns, visibleColumns, columnOrder]);

  // 构建分页配置
  const pagination = useMemo(() => {
    if (propPagination === false) return false;

    // 用户配置优先，确保用户设置能够覆盖默认值
    const userPagination = typeof propPagination === 'object' ? propPagination : {};
    console.log('userPagination:', userPagination);
    return {
      // 先应用用户配置
      ...userPagination,
      // 然后设置必要的内部属性和默认值
      current: currentPage,
      pageSize: pageSize,
      total: total,
      // showTotal: (total: number) => `共 ${total} 条数据`,
      onChange: handlePaginationChange,
      onShowSizeChange: handlePaginationChange,
      // 只有在用户没有明确设置时才应用默认值
      showSizeChanger: userPagination.showSizeChanger !== undefined ? userPagination.showSizeChanger : true,
      showQuickJumper: userPagination.showQuickJumper !== undefined ? userPagination.showQuickJumper : true,
    };
  }, [currentPage, pageSize, total, propPagination]);

  // 构建工具栏按钮
  const toolBarButtons = useMemo(() => {
    const buttons: ReactNode[] = [];
    // 添加用户自定义的工具栏按钮
    if (toolBarRender) {
      buttons.push(...toolBarRender());
    }
    buttons.push(
      <Popover
        key="setting"
        content={renderColumnSettings()}
        title="列设置"
        trigger="click"
        open={settingPopoverVisible}
        onOpenChange={setSettingPopoverVisible}
        zIndex={1000}
      >
        <Button icon={<SettingOutlined />} onClick={() => setSettingPopoverVisible(true)}>
          列设置
        </Button>
      </Popover>
    );

    return buttons;
  }, [toolBarRender, settingPopoverVisible, visibleColumns, columnOrder]);

  // 组件挂载时加载数据
  useEffect(() => {
    loadData({ page: currentPage, pageSize, ...searchParams });
    console.log(pagination, 'pagination');
  }, []);

  return (
    <div className="list-table-container">
      {/* 工具栏 */}
      {(toolBarButtons.length > 0 || tableProps.rowSelection) && (
        <Row gutter={[16, 16]} align="middle" justify="space-between" style={{marginBottom:16}} >
          <Col>{tableTitle || '列表'}</Col>
          <Col>
            <Space>{toolBarButtons}</Space>
          </Col>
        </Row>
      )}
      {/* 表格 */}
      <Table
        columns={tableColumns}
        dataSource={propDataSource || data}
        loading={loading}
        pagination={pagination}
        rowKey="id"
        {...tableProps}
        locale={{
          emptyText: <Empty description="暂无数据" />
        }}
      />
      {/* <div>共 {total} 条数据 </div> */}
    </div>
  );
};

export default ListTable;
export type { ListTableColumn, ListTableProps };